<template>
  <div id="FunctionModule">
    <Breadcrumb :content="content"></Breadcrumb>
    <div class="bodyContent skin-green">
      <Splitpanes style="height: 100%">
        <Pane :size="(800 / conWidth) * 100">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">不合格原因组</div>
              <vxe-input
                clearable
                placeholder="关键字查询"
                class="vxeInputSearch"
                v-model="keywords"
                @search-click="search"
                @keyup="keyup"
                type="search"
              ></vxe-input>

              <vxe-button
                type="text"
                class="button-blue"
                icon="vxe-icon-refresh"
                content="刷新"
                :loading="showLoading"
                @click="handleSearch"
              ></vxe-button>
              <vxe-button
                type="text"
                class="button-blue"
                icon="vxe-icon-square-plus"
                content="新建"
                @click="handleAdd('')"
              ></vxe-button>
              <vxe-button
                type="text"
                icon="vxe-icon-save"
                content="保存"
                :loading="saveLoading"
                class="button-blue"
                @click="saveList"
              ></vxe-button>
              <vxe-button
                type="text"
                class="button-red"
                icon="vxe-icon-delete"
                content="删除"
                @click="handleDelete"
              ></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="modulTable">
            <vxe-table
              ref="unqualifiedTable"
              border="inner"
              height="auto"
              class="mytable-scrollbar"
              :loading="showLoading"
              :data="UnqualifiedList"
              @current-change="moduleRowClick"
              :row-config="{ isCurrent: true, isHover: true }"
              :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }"
              :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showIcon: false,
                showStatus: true
              }"
              :edit-rules="formRule"
              resizable
              show-overflow
              keep-source
            >
              <vxe-column type="checkbox" width="50" align="center"></vxe-column>
              <vxe-column type="seq" title="序号" width="30" align="center"></vxe-column>

              <vxe-column
                field="unqualifiedCode"
                title="不合格类型"
                width="140"
                align="center"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
              >
                <template #default="{ row }">
                  <span>{{ row.unqualifiedName }}</span>
                </template>
                <template #edit="{ rowIndex }">
                  <SelectDataGrid
                    :url="'/api/sys/basDictDetail/findDictDetailList'"
                    :column="[
                      { field: 'code', title: '编码' },
                      { field: 'name', title: '名称' }
                    ]"
                    :searchParam="{ code: 'BHGJLLX' }"
                    :isPage="false"
                    @SelectCellClick="
                      (e) => {
                        selectRow(e, rowIndex);
                      }
                    "
                  >
                  </SelectDataGrid>
                </template>
              </vxe-column>

              <vxe-column
                field="unqualifiedGroup"
                title="不合格原因组名称"
                width="150"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
                align="center"
              >
                <template #default="{ row }">
                  <span>{{ row.unqualifiedGroup ? row.unqualifiedGroup : '' }}</span>
                </template>
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input
                    v-model="row.unqualifiedGroup"
                    @blur="unqualifiedHandleBlur(row, rowIndex)"
                    type="text"
                  ></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="groupCode" title="编码" width="120" align="center">
                <template #default="{ row }">
                  <span>{{ row.groupCode ? row.groupCode : '' }}</span>
                </template>
              </vxe-column>
              <vxe-column
                field="inputCode"
                title="助记符"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
                align="center"
              >
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input
                    v-model="row.inputCode"
                    type="text"
                    @keydown.enter="enterEvent(row, rowIndex, column)"
                  ></vxe-input>
                </template>
              </vxe-column>

              <vxe-column
                field="seq"
                title="顺序号"
                min-width="50"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
                align="center"
              >
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input
                    v-model="row.seq"
                    type="text"
                    @keydown.enter="enterEvent(row, rowIndex, column)"
                  ></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 原因 -->
        <Pane>
          <LabUnqualifiedReasonList ref="refUnqualifiedReason"></LabUnqualifiedReasonList>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import LabUnqualifiedReasonList from './LabUnqualifiedReasonList.vue';
import Breadcrumb from '../../../components/Breadcrumb.vue';
import VxePulldownSelection from '../../../components/VxePulldownSelection.vue';
import VxePulldownSelectIconfont from '../../../components/VxePulldownSelectIconfont.vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
import SelectByDepList from '@/components/SelectByDepList.vue';
import SelectIcon from '../../../components/SelectIcon.vue';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import SelectDataGrid from '@/components/SelectDataGrid.vue';

let store = AppStore();
let { proxy }: any = getCurrentInstance();

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

// 子组件ref名称
let refselectIcon = ref(null);

// 页面标题
let content = ref('不合格记录设置');
// 用户输入关键字
let keywords = ref('');

// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let saveLoading = ref(false); //保存

//**判断为空*/
let IsEmpty = (value: any) => {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
};

onMounted(() => {
  getUnqualifiedList();
  // getModulePointMap();
});

// 表格规则
let formRule = ref({
  unqualifiedName: [
    {
      required: true,
      message: '请输入不合格组名称',
      trigger: 'blur'
    }
  ]
});
// function getUnqualifiedList() {
//   if (Object.keys(modulePointMap).includes(moduleId)) {
//     modulePoitPre.push(...modulePointMap[moduleId]);
//   }
// }
// 模块功能表格数据
let UnqualifiedList: any = reactive([]);
function unqualifiedHandleBlur(row: any, rowIndex) {
  if (!IsEmpty(row.unqualifiedGroup)) {
    UnqualifiedList[rowIndex].inputCode = funBdsJsResult('firstPinYinFun', row.unqualifiedGroup);
  }
}

// 请求表格数据
function getUnqualifiedList() {
  showLoading.value = true;
  let pageParam = {
    params: {
      keywords: keywords.value
    }
  };
  UnqualifiedList.length = 0; //放入数据前清空数组
  proxy.$http.get('/lab/unqualified/group/getUnqualifiedListNoPage', pageParam).then((res: any) => {
    if (res.status.code === 200) {
      showLoading.value = false;
      // console.log('模块数据列表', res.status.code);
      UnqualifiedList.push(...res.data);
      moduleRowClick({ row: UnqualifiedList[0], rowIndex: 0 });
      // VXETable.modal.message({ content: res.status.msg, status: 'success' });
    } else {
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}

// 当前选中行的下标
let clickIndex = null;
let refUnqualifiedReason: any = ref(null);
// 点击行
function moduleRowClick({ row, rowIndex }) {
  clickIndex = rowIndex;
  let $Xtable = proxy.$refs.unqualifiedTable;
  $Xtable.setCurrentRow(row);
  refUnqualifiedReason.value.initPage(row.id); //调用菜单组件方法
}
// 点击刷新
function handleSearch() {
  getUnqualifiedList();
}
let unqualifiedTable = ref();
// 点击新增
async function handleAdd(row: any) {
  const record = {
    unqualifiedCode: '',
    unqualifiedName: '',
    unqualifiedGroup: '',
    inputCode: '',
    seq: UnqualifiedList.length + 1, //排序号
    id: '',
    unqualifiedReasonId: '',
    groupCode: ''
  };
  UnqualifiedList.push(record);
}

// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.unqualifiedTable;
  let selectRows = $Xtable.getCheckboxRecords();
  let ids = '';
  let names = '';
  // const data = {ids:'',names:''};

  if (selectRows <= 0) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    selectRows.forEach((row) => {
      // 对每一行执行特定操作
      console.log('row-----------', row);
      ids += row.id + ',';
      names += row.unqualifiedGroup + ',';

      // 其他操作...
    });
    // 去掉最后一个逗号
    ids = ids.slice(0, -1);
    names = names.slice(0, -1);
    let data = { ids: ids, names: names };
    proxy
      .$confirm('确定删除此条用户数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        proxy.$http
          .post('/lab/unqualified/group/daleteGroup/', data)
          .then((res: any) => {
            if (res.status.code === 400) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getUnqualifiedList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage('删除异常', VxeNotifyType.error);
          });
      });
  }
}
function selectRow(e, rowIndex) {
  if (!IsEmpty(e)) {
    UnqualifiedList[rowIndex].unqualifiedCode = e.code;
    UnqualifiedList[rowIndex].unqualifiedName = e.name;
  }
}
// 点击修改保存
async function saveList() {
  saveLoading.value = true;
  // 获取表格实例
  let $Xtable = proxy.$refs.unqualifiedTable;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = UnqualifiedList.filter((e: any) => {
      return e.id === '';
    });
    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    let UpgroupNames = '';
    if (updateRecords.length > 0) {
      updateRecords.forEach((record) => {
        UpgroupNames += record.unqualifiedGroup + ',';
      });
      UpgroupNames = UpgroupNames.slice(0, -1);
      const reqData = { unqualifiedGroups: updateRecords, groupNames: UpgroupNames };
      proxy.$http
        .post('/lab/unqualified/group/updateGroup', reqData)
        .then((res: any) => {
          console.log('res=--------', res);

          if (res.status.code === 400) {
            VxeMessage('修改成功', VxeNotifyType.success);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    }
    let AddGroupNames = '';
    if (InsertRecords.length > 0) {
      InsertRecords.forEach((record) => {
        AddGroupNames += record.unqualifiedGroup + ',';
      });
      AddGroupNames = AddGroupNames.slice(0, -1);
      const reqData = { unqualifiedGroups: InsertRecords, groupNames: AddGroupNames };
      proxy.$http
        .post('/lab/unqualified/group/addGroup', reqData)
        .then((res: any) => {
          if (res.status.code === 400) {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增异常', VxeNotifyType.error);
        });
    }
    setTimeout(() => {
      getUnqualifiedList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

// 关键字搜索
function search() {
  getUnqualifiedList();
}

function keyup(e: any) {
  if (e.$event.code == 'Enter') {
    search();
  }
}
</script>
<style lang="scss" scoped>
#FunctionModule {
  height: 100%;
  width: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
  }
  // 左边表格
  .modulTable {
    height: calc(100% - 39px);
    background-color: $base-white;
  }
}
</style>
